
//添加博客
function addBlog() {
    location.href = "/admin/edit";
}

// Tags Input,让标签独立化，同时可以加入多个标签
$('#blogTags').tagsInput({
    width: '100%',
    height: '38px',
    defaultText: '文章标签'
});

//修改博客
function updateBlog() {
    if($('input[name="checkOption"]:checked').length > 1){
        swal("一次只能修改一篇博客",{
            icon: "warning",
            button: {
                text: "好的",
            },
        })
        return;
    }
    let blogId = $('input[name="checkOption"]:checked').parent("th").parent("tr").find("[name='id']").html();
    if(blogId == "" || blogId == null || blogId == undefined){
        swal("请至少选择一个博客修改",{
            icon: "warning",
            button: {
                text: "好的",
            },
        })
        return;
    }

    location.href = "/admin/blog/update/" + blogId;
}

//删除博客
function deleteBlog() {
    let ids = new Array();
    $('input[name="checkOption"]:checked').each(function () {
        ids.push($(this).parent("th").parent("tr").find("[name='id']").html());
    })

    if (ids.length == 0 ){
        swal("请至少选择一篇文章删除",{
            icon: "warning",
            button: {
                text: "好的",
            },
        })
        return;
    }

    swal({
        title: "你确定要删除吗？",
        text: "你将无法恢复它！",
        icon: "warning",
        buttons: ["我点错了","确认删除"],
        dangerMode: true,
    }).then(flag => {
        if(flag){
            $.ajax({
                type: "post",
                url: "/admin/blog/delete",
                data: {"ids" : ids},
                traditional: true,
                success: function (result) {
                    if(result.resultCode == 200){
                        swal("删除成功",{
                            icon: "success",
                            button: {
                                text: "好的",
                            },
                        }).then(function () {
                            location.reload();
                        })
                    }else {
                        swal(result.message,{
                            icon: "error",
                            button: {
                                text: "好的",
                            },
                        })
                    }
                },
                error: function () {
                    swal("操作失败", {
                        icon: "error",
                        button: {
                            text: "好的"
                        },
                    });
                }
            })
        }
    })
}

//搜索框搜索给定关键字的博客
function search() {
    //获取搜索框内的内容
    let keyword = $("#keyword").val();
    //转发请求加上参数
    location.href = "/admin/blog/" + keyword;

}

$("#cancelButton").click(function () {
    location.href = "/admin/blog";
})

//增加博客
$("#confirmButton").click(function () {
    let blogName = $("#blogName").val();
    let blogTags = $("#blogTags").val();
    // 将来访问博客的资源路径
    //let blogSubUrl = $("#blogSubUrl").val();
    let blogCategoryId = $("#blogCategoryId").val();
    let content = $("#content").val();
    if(isNull(blogName)){
        tip("请输入标题");
        return;
    }
    if(validLength(blogName,50)){
        tip("标题长度超出范围");
        return;
    }
    if(isNull(blogTags)){
        tip("请输入标签");
        return;
    }
    if(validLength(blogTags,100)){
        tip("标签长度超出范围");
        return;
    }
    if(isNull(content)){
        tip("请输入文章内容");
        return;
    }
    if(validLength(content,100000)){
        tip("文章长度超出范围");
        return;
    }
    $('#articleModal').modal('show');

})

//完善需要发布的博客信息后的确认键
$('#saveButton').click(function () {
    //获得文章id
    let blogId = $("#blogId").val();
    //获得文章标题
    let blogTitle = $("#blogName").val();
    //获得文章标签
    let blogTags = $("#blogTags").val();
    //将来访问博客的资源路径
    //let blogSubUrl = $("#blogSubUrl").val();
    //获得文章分类id
    let blogCategoryId = $("#blogCategoryId").val();
    //获得文章内容
    let blogContent = $("#content").val();
    //$("#content").innerText = "这是一个测试";
    //获得文章背景图
    let blogCoverImage = $("#blogCoverImage")[0].src;
    //获得文章的状态
    let blogStatus = $("input[name='blogStatus']:checked").val();
    //获得文章是否可以评论
    let enableComment = $("input[name='enableComment']:checked").val();

    //indexOf() 方法是查询一个字符串中是否含有我给定的字符串，返回首次出现的位置，如果没有找到就返回-1
    if(isNull(blogCoverImage) || blogCoverImage.indexOf("/admin/img/img-upload.png") != -1){
        tip("封面图片不能为空");
        return;
    }

    $.ajax({
        type: "post",
        url: "/admin/blog/save",
        data: {"blogId" : blogId,"blogTitle" : blogTitle,"blogCoverImage" : blogCoverImage,"blogContent" : blogContent,"blogCategoryId" : blogCategoryId,"blogTags" : blogTags,"blogStatus" : blogStatus,"enableComment" : enableComment},
        success: function (result) {
            if(result.resultCode == 200){
                $('#articleModal').modal('hide');
                swal("保存成功",{
                    icon: "success",
                    button: {
                        text: "返回文章列表",
                    },
                }).then(function () {
                    location.href = "/admin/blog";
                })
            }else {
                $('#articleModal').modal('hide');
                tip(result.message);
            }
        },
        error: function () {
            $('#articleModal').modal('hide');
            tip("操作失败");
        }
    })

})


//随机封面的功能
$('#randomCoverImage').click(function () {
    let rand = parseInt(Math.random() * 40 + 1);
    //attr() 设置选中的标签的属性值
    $("#blogCoverImage").attr("src", '/admin/img/rand/' + rand + ".jpg");
    $("#blogCoverImage").attr("style", "width:160px ;height: 120px;display:block;");
});


// 点击上传图片，触发图片选择器
function selectImage() {
    $("#select").click();
}

function uploadImage() {
    // $("#select").val() 获取的是你上传图片的路径名+文件名
    let path = $("#select").val();
    if (isNull(path)) {
        return;
    }
    // 创建一个表单存储的空对象
    let formData = new FormData();
    // formData 里面存储形式为 {"key":"value"}
    formData.append("file",document.getElementById('select').files[0]);
    // 定义检测上传文件是否为图片的正则表达式
    let pattern = /\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/;
    // 检测获取的文件名是否为图片
    if (!pattern.test(path)) {
        tip("请选择图片上传");
        return;
    }
    $.ajax({
        method: "post",
        url: "/admin/blog/blogCoverImage",
        data: formData,
        contentType: false,
        processData: false,
        success: function (result) {
            if (result.isSuccess == 1) {
                $("#blogCoverImage").attr("src",result.url);
                $("#blogCoverImage").attr("style", "width: 128px;height: 128px;display:block;");
            }else {
                tip("上传失败，请重试");
            }
        }
    })
}


//提示消息方法
function tip(msg) {
    swal(msg,{
        icon: "error",
        button: {
            text: "好的"
        }
    })
}

//判断变量是否为空
function isNull(obj) {
    if(obj.trim() == "" || obj == null || obj == undefined){
        return true;
    }
    return false;
}

//判断变量长度是否超过了给定长度
function validLength(obj, length) {
    if(obj.trim().length > length){
        return true;
    }
    return false;
}






